package cjyyp.day01;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class 两阶段终止模式 {
    public static void main(String[] args) throws InterruptedException {
        TerminationMode terminationMode=new TerminationMode();
        terminationMode.start();
        Thread.sleep(5000L);
        terminationMode.stop();
    }
}

/**
 * 两阶段终止模式实现类
 * 一般用于后台监控
 */
@Slf4j
class TerminationMode{
    private Thread thread;
    //开启监控线程
    public void start(){
        thread=new Thread(()->{
            Thread t = Thread.currentThread();
            //轮询监控
            while (true){
                if(t.isInterrupted()==true){
                    log.debug("监控线程被打断了。");
                    break;
                }
                try {
                    Thread.sleep(2000L);
                    log.debug("正在监控系统。");
                } catch (InterruptedException e) {
                    t.interrupt();
                }
            }
        });

        thread.start();
    }
    public void stop(){
        thread.interrupt();
    }
}
